package com.example.excise06.security;

import com.example.excise06.repository.UserRepository;
import com.example.excise06.repository.UserRoleRepository;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class TokenProvider{
    @Resource
    private UserRepository userRepository;

    @Resource
    private UserRoleRepository userRoleRepository;

    public String createToken(Authentication user) {
        return "thisistoken." + user.getName();
    }

    // 校验用户令牌是否合法
    public boolean validateToken(String token) {
        return token.startsWith("thisistoken");
    }

    public Authentication getUser(String token) {
        // 1. 解析令牌。搭配SpringSecurity能够使用的Authentication，实现逻辑与UserDetailService类似
        String login = token.split("\\.")[1];
        String roleString = token.split("\\.")[2];
        roleString = roleString.replace("[", "").replace("]", "");
        // 2. 获取账户对应角色
        String[] roles = roleString.split("，");
        //将账户角色组成SpringSecurity的权限列表
        List<SimpleGrantedAuthority> roleList = new ArrayList<SimpleGrantedAuthority>();
        for (Integer i = 0; i < roles.length; i++) {
            roleList.add(new SimpleGrantedAuthority(roles[1]));
        }
        Authentication user = new UsernamePasswordAuthenticationToken(login, token, roleList);
        return user;
    }
}